package com.jit.app.frament;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jit.app.AppDetailActivity;
import com.jit.app.PublicCommentActivity;
import com.jit.app.R;
import com.jit.app.ReplayListActivity;
import com.jit.app.adapter.CommentListAdapter;
import com.jit.app.model.AppInfoModel;
import com.jit.app.model.Constants;
import com.jit.app.util.InstalledApplicationUtils;
import com.jit.app.util.JSONResult;
import com.jit.app.util.LoginUtils;


import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommentFragment extends Fragment {

    public static final int REQUEST_COMMENT_CODE = 100;
    AppDetailActivity activity;
    View view;
    Handler handler;
    AppInfoModel model = new AppInfoModel();;
    ListView commentListView;
    CommentListAdapter commentListAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (AppDetailActivity) getActivity();
        view = inflater.inflate(R.layout.fragment_comment, null);

        initView();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch(msg.what){
                    case Constants.MessageWhat.COMMENTSTATISTIC_LOAD_SUCCESS:
                        JSONResult jsonResult = (JSONResult) msg.obj;
                        if(jsonResult.getCode() == Constants.ResultCode.SUCCESS){
                            JSONArray result = (JSONArray) jsonResult.getData().get("commentStatistic");
                            List<JSONObject> list = result.toJavaList(JSONObject.class);
                            int total = 0;//总评论数
                            int totalScore = 0;
                            for(JSONObject obj : list){
                                total += obj.getInteger("cnt");
                                totalTextView.setText(total + "人评分");
                            }
                            for(JSONObject obj : list){
                                int stars = obj.getInteger("stars");
                                int cnt = obj.getInteger("cnt");
                                int rate = (int)(cnt*1.0/total*100);
                                switch(stars){
                                    case 1:
                                        stars1Provess.setProgress(rate);
                                        totalScore += cnt * 1;
                                        break;
                                    case 2:
                                        stars2Provess.setProgress(rate);
                                        totalScore += cnt * 2;
                                        break;
                                    case 3:
                                        stars3Provess.setProgress(rate);
                                        totalScore += cnt * 3;
                                        break;
                                    case 4:
                                        stars4Provess.setProgress(rate);
                                        totalScore += cnt * 4;
                                        break;
                                    case 5:
                                        stars5Provess.setProgress(rate);
                                        totalScore += cnt * 5;
                                        break;
                                }
                            }

                            double avgScore = totalScore*1.0/total;
                            NumberFormat numberFormat = new DecimalFormat("######0.0");
                            String format = numberFormat.format(avgScore);
                            scoreTextView.setText(format);
                        }
                    break;
                    case Constants.MessageWhat.COMMENTLIST_LOAD_SUCCESS:
                        JSONResult jsonResult2 = (JSONResult) msg.obj;
                        if(jsonResult2.getCode() == Constants.ResultCode.SUCCESS){
                            JSONArray result = (JSONArray) jsonResult2.getData().get("appCommentListForPage");
                            List<JSONObject> list = result.toJavaList(JSONObject.class);
                            commentListAdapter = new CommentListAdapter(activity, R.layout.item_commentlist, list);
                            commentListView.setAdapter(commentListAdapter);
                        }
                        break;

                    case Constants.MessageWhat.USERCOMMENT_LOAD_SUCCESS:
                        JSONResult jsonResult3 = (JSONResult) msg.obj;
                        if(jsonResult3.getCode() == Constants.ResultCode.SUCCESS){
                            userComment = (Map) jsonResult3.getData().get("userComment");
                            myScoreRatingBar.setRating((Integer)userComment.get("stars"));
                            alertInfoTextView.setText("已评论");
                        }
                        break;
                    case Constants.MessageWhat.LOGIN_LOAD_SUCCESS:
                        JSONResult jsonResult4 = (JSONResult) msg.obj;
                        if(jsonResult4.getCode() == Constants.ResultCode.SUCCESS){
                            Map userInfo = (Map) jsonResult4.getData().get("userInfo");
                            alertDialog.cancel();
                            //把用户信息存储到SharedPreferences
                            LoginUtils.saveLoginInfo(activity, userInfo);
                            isLogin = true;
                            //更新下界面中的相关信息
                            String picPath = (String) userInfo.get("picPath");
                            if (picPath != null){
                                Glide.with(activity).load(Constants.HOST.FILE_HOST+picPath).into(headPicImageView);
                            }
                            loginTextView.setText(userInfo.get("nickName").toString());
                            //跳到评论页面
                            Intent intent = new Intent(activity, PublicCommentActivity.class);
                            intent.putExtra("appInfo",(HashMap)activity.appInfo);
                            intent.putExtra("userInfo", JSONObject.parseObject(LoginUtils.isLogin(activity), HashMap.class));
                            startActivityForResult(intent,REQUEST_COMMENT_CODE);

                        }else if(jsonResult4.getCode() == Constants.ResultCode.INVALID_AUTH){
                            loginError.setText("用户名或者密码错误");
                        }
                        break;
                }
                return true;
            }
        });


        initData();
        return view;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_COMMENT_CODE){
            if(resultCode == PublicCommentActivity.PUBLIC_RESULT_CODE){
                Map commentInfo = (Map) data.getSerializableExtra("commentInfo");
                //更新一下评论列表
                commentListAdapter.getList().add(0,JSONObject.parseObject(JSONObject.toJSONString(commentInfo)));
                commentListAdapter = new CommentListAdapter(activity,R.layout.item_commentlist, commentListAdapter.getList());
                commentListView.setAdapter(commentListAdapter);
                myScoreRatingBar.setRating((Integer)commentInfo.get("stars"));
            }else if(resultCode == PublicCommentActivity.CANCEL_RESULT_CODE){
                Toast.makeText(activity, "不发表评论", Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    TextView scoreTextView;
    TextView totalTextView;
    ProgressBar stars5Provess;
    ProgressBar stars4Provess;
    ProgressBar stars3Provess;
    ProgressBar stars2Provess;
    ProgressBar stars1Provess;

    ScrollView scrollView;

    ImageView headPicImageView;
    TextView loginTextView;
    RatingBar myScoreRatingBar;
    TextView alertInfoTextView;

    boolean isInstalled = false;;
    boolean isLogin = false;
    Map userComment;

    AlertDialog alertDialog;
    TextView loginError;
    private void initView(){
        scrollView = (ScrollView) view;
        scrollView.smoothScrollTo(0,0);


        scoreTextView = view.findViewById(R.id.tv_score);
        totalTextView = view.findViewById(R.id.tv_total);

        stars1Provess = view.findViewById(R.id.pb_stars1);
        stars2Provess = view.findViewById(R.id.pb_stars2);
        stars3Provess = view.findViewById(R.id.pb_stars3);
        stars4Provess = view.findViewById(R.id.pb_stars4);
        stars5Provess = view.findViewById(R.id.pb_stars5);


        commentListView = view.findViewById(R.id.lv_commentlist);
        commentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(activity, ReplayListActivity.class);
                intent.putExtra("commentInfo",(JSONObject)parent.getItemAtPosition(position));
                activity.startActivity(intent);
            }
        });


        headPicImageView = view.findViewById(R.id.iv_headpic);
        loginTextView = view.findViewById(R.id.tv_login);
        myScoreRatingBar = view.findViewById(R.id.rb_score);
        alertInfoTextView = view.findViewById(R.id.tv_alertinfo);


        if(InstalledApplicationUtils.isInstalled(activity.appInfo.get("apkName").toString(), activity)){
            alertInfoTextView.setText("已安装，可以评论");
            isInstalled = true;
        }


        final String userInfo = LoginUtils.isLogin(activity);
        JSONObject jsonObject = null;
        if(userInfo != null){
            jsonObject = JSONObject.parseObject(userInfo);
            String picPath = jsonObject.getString("picPath");
            if(picPath != null){
                Glide.with(activity).load(Constants.HOST.FILE_HOST+picPath).into(headPicImageView);
            }
            loginTextView.setText(jsonObject.getString("nickName"));
            isLogin = true;
        }

        if(isInstalled && isLogin){
            model.loadAppUserComment(handler, (Integer)activity.appInfo.get("id"), jsonObject.getLong("id") );
        }

        RelativeLayout myComment = view.findViewById(R.id.rl_mycomment);
        myComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isInstalled){
                    Toast.makeText(activity, "请先安装app，才能评论", Toast.LENGTH_SHORT).show();
                }else if(!isLogin){
                    //跳到登陆页面(登陆对话框)

                    View layout = LayoutInflater.from(activity).inflate(R.layout.dialog_login,null);
                    final EditText usernameTextView = layout.findViewById(R.id.et_username);
                    final EditText passwordTextView = layout.findViewById(R.id.et_password);
                    Button okBtn = layout.findViewById(R.id.btn_ok);
                    Button cancelBtn = layout.findViewById(R.id.btn_cancel);
                    loginError = layout.findViewById(R.id.tv_loginerror);
                    okBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String username = usernameTextView.getText().toString();
                            String password = passwordTextView.getText().toString();
                            model.login(handler, username, password);
                        }
                    });
                    cancelBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.cancel();
                        }
                    });
                    alertDialog = new AlertDialog.Builder(activity)
                            .setTitle("登陆")
                            .setView(layout)
                            .setCancelable(false)
                            .show();
                }else{
                    //跳转到评论页面
                    Intent intent = new Intent(activity, PublicCommentActivity.class);
                    intent.putExtra("appInfo",(HashMap)activity.appInfo);
                    intent.putExtra("userInfo", JSONObject.parseObject(userInfo, HashMap.class));
                    startActivityForResult(intent,REQUEST_COMMENT_CODE);
                }
            }
        });
    }

    private void initData(){
        model.loadCommentScoreList(handler, (Integer)activity.appInfo.get("id"));
        model.loadCommentList(handler,  (Integer)activity.appInfo.get("id"));
    }

}
